package org.yes.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * User: mtymes
 * Date: May 27, 2010
 * Time: 9:01:06 AM
 */
public class AnnotationUtil {

    /* ====================== */
    /* --- public methods --- */
    /* ====================== */


    public static <A extends Annotation> Map<Field, A> findAnnotatedFields(final Class beanClass, final Class<A> annotationClass) {
        Map<Field, A> annotatedFields = new LinkedHashMap<Field, A>();

        for (Field field : ReflectionUtil.getDeclaredFields(beanClass)) {
            A annotation = getAnnotation(field, annotationClass);

            if (annotation != null) {
                annotatedFields.put(field, annotation);
            }
        }

        return annotatedFields;
    }


    public static <A extends Annotation> Map<Method, A> findAnnotatedMethods(final Class beanClass, final Class<A> annotationClass) {
        Map<Method, A> annotatedMethods = new LinkedHashMap<Method, A>();

        for (Method method : ReflectionUtil.getMethods(beanClass)) {
            A annotation = getAnnotation(method, annotationClass);

            if (annotation != null) {
                annotatedMethods.put(method, annotation);
            }
        }

        return annotatedMethods;
    }


    /* ====================== */
    /* --- helper methods --- */
    /* ====================== */


    private static <A extends Annotation> A getAnnotation(final Field field, final Class<A> annotationClass) {
        return field.getAnnotation(annotationClass);
    }


    private static <A extends Annotation> A getAnnotation(final Method method, final Class<A> annotationClass) {
        return method.getAnnotation(annotationClass);
    }
}
